#include <thread>


#include "TaskUninstallapp.h"
#include "App.h"
#include "AdbHelper.h"
#include "ServiceConnection.h"


namespace Gnodroid {

    TaskUninstallapp::TaskUninstallapp(std::string appPid):
        Task(TaskProgressType::NONE)
    {
        m_appPid = appPid;
    }

    void
    TaskUninstallapp::start()
    {
        updateState(TaskState::RUNNING);
        updateLabel(std::string("Uninstall app: ") + m_appPid);
        updateMessage("uninstalling");

        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(App::getService(SERVICE_CONNECTION));

        if (!serviceConnection->isConnecting()) {
            updateMessage("Not connected");
            updateState(TaskState::ERROR);
            return;
        }

        std::thread t(sigc::mem_fun(*this, &TaskUninstallapp::__uninstallAppThread));
        t.detach();
        return;
    }

    void
    TaskUninstallapp::__uninstallAppThread()
    {
        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(
                    App::getService(SERVICE_CONNECTION));

        if (!AdbHelper::uninstallApp(serviceConnection->getAdbPath(),
                                     serviceConnection->getDeviceId(),
                                     m_appPid)) {
            updateMessage("Uninstall app failed");
            updateState(TaskState::ERROR);
            return;
        }

        updateMessage("Success");
        updateState(TaskState::FINNISHED);
        return;
    }
}
